createVariantDocument
- ๐ฌ๐ง English
- ๐ฎ๐น Italian
Function Name: createOrUpdateVariantDocument
Author: Domenico Cerone Creation Date: 25/09/2025
Last Reviewer: Domenico Cerone
Trigger: Called by populateVariantFromSku and populateVariantFromExcel
Purpose: Manages creation and updating of documents in the 'Variants' Firestore collection from mapped JSON data generated by populateVariantFromSku. Handles complete variant lifecycle with automatic tag management, brand integration, and comprehensive field mapping.
Detailed Functionalityโ
This component function handles the complete Variants collection management with a sophisticated 3-step workflow for both new variants and existing variant updates. Includes thread-safe tag creation system and brand normalization to ensure data consistency in high-concurrency scenarios.
1. DOCUMENT EXISTENCE CHECKโ
- Searches in 'Variants' collection for document with skuModel equal to provided value
- If EXISTS โ updates only necessary fields (STEP 3)
- If NOT EXISTS โ creates new complete document (STEP 2)
2. NEW DOCUMENT CREATIONโ
- Creates document with complete base structure
- Populates only mapped fields from JSON, leaves others empty
- Uses Firestore auto-generated ID
- Sets status = "Incompleto"
3. EXISTING DOCUMENT UPDATEโ
- Updates only fields that come from mapped JSON
- Maintains all other existing fields unchanged
- Updates lastUpdate with current timestamp
Fields Populated from Mapped JSONโ
Directly Mapped Fieldsโ
- skuModel โ skuModel (main identifier)
- eanCode โ eanCode
- frameColor โ frameColor
- lensesColor โ lensesColor
- glassesName โ glassesName
- mainBrandRef โ Brand ID (find/create in MainBrands collection)
- upcCode โ upcCode
- batch โ batch (value from CatalogOrder or input parameter)
- productRef โ Parent Products document ID
- catalogOrdersRef โ CatalogOrder ID that generated the variant
- poster โ poster (view 00 - main frontal)
- poster2 โ poster2 (view 07 - lateral angle)
- poster3 โ poster3 (view 02 - frontal detail)
- poster4 โ poster4 (view 01 - alternative angle)
Timestamp Fields (with conversion)โ
- lastUpdate โ current timestamp (Date object)
- skuReleaseDate โ skuReleaseDate (if present, Date object)
- skuEndDate โ skuEndDate (if present, Date object)
- advStartDate โ advStartDate (if present, Date object)
- advEndDate โ advEndDate (if present, Date object)
Boolean Fieldโ
- isADV โ isADV (converted from "YES"/"NO" to boolean)
Size Object (all fields as strings)โ
- size.bridge โ bridge
- size.frameWidth โ frameWidth
- size.lensHeight โ lensHeight
- size.lensWidth โ lensWidth
- size.size โ size
- size.templeLength โ templeLength
- size.frontHeight โ frontHeight
- size.hingeToHinge โ hingeToHinge
- size.lensCircumference โ lensCircumference
- size.lensAngle โ lensAngle
- size.phantoscopicAngle โ phantoscopicAngle
Special Arraysโ
- list_size_color_tags โ [frameColor tag ID, size tag ID] (find/create in Tags collection)
- list_images โ list_images (array of objects with view and url)
Tag Management Systemโ
The function automatically creates/finds tags in the Tags collection:
Frame Color Tagsโ
- Group: "Frame Color"
- Type: "frameColor"
- GroupOrder: 11
- Name: frameColor value (e.g., "BLACK", "BURGUNDY 2")
Size Tagsโ
- Group: "Size"
- Type: "size"
- GroupOrder: 10
- Name: size value (e.g., "54", "99")
Base Document Structureโ
All other fields maintain default values:
- assignedTo: ""
- assignmentDate: ""
- dataTaken: false
- id: "" (auto-generated by Firestore)
- loadingId: ""
- mainModel: false
- modelPriority: ""
- modelViewerUrl: ""
- modify_model: { rejectCount: "", requestCount: "", status: "" }
- posterNoBackground: ""
- primaryFrameColorHex: ""
- primaryLensesColorHex: ""
- priority: 0
- productRef: ""
- refLogVariant: ""
- secondaryFrameColorHex: ""
- secondaryLensesColorHex: ""
- status: "Incompleto"
- templeColor: ""
- urlDE: ""
- urlES: ""
- urlFR: ""
- urlGlobal: ""
- urlGlobalComplete: ""
- urlGlobalCompleteSize: 0
- urlGlobalSize: 0
- urlProductPage: ""
- urlUsdz: ""
- urlUsdzComplete: ""
- urlUsdzCompleteSize: 0
- urlUsdzSize: 0
- variantCode: ""
- list_notes: []
Function Parametersโ
/**
* @param {Object} mappedJsonData - Mapped JSON data from populateVariantFromSku
* @param {string} requestId - Request ID for logging
* @param {string} batch - Variant batch assignment (optional)
* @param {string} productRef - Parent Products document ID (optional)
* @param {string} catalogOrdersRef - CatalogOrder ID that generated the variant (optional)
* @returns {Promise<Object>} Operation result with details
*/
Date Field Conversionโ
Timestamp fields are automatically converted from various formats to JavaScript Date objects:
Supported Input Formatsโ
- Number: Unix timestamp in milliseconds
- String: ISO 8601 date string (e.g., "2025-08-01T02:00:00")
- Empty/null: Remains empty
Automatic Conversionโ
- All date fields are converted to JavaScript Date objects
- Empty or invalid dates remain as empty strings
- Current timestamp used as fallback for conversion errors
Image Managementโ
The function handles image arrays from the mapped JSON:
list_images Structureโ
[
{
"view": "00",
"url": "https://firebasestorage.googleapis.com/.../image_00.jpg?token=xxx"
},
{
"view": "01",
"url": "https://firebasestorage.googleapis.com/.../image_01.jpg?token=yyy"
},
{
"view": "02",
"url": "https://firebasestorage.googleapis.com/.../image_02.jpg?token=zzz"
}
]
Poster Fieldsโ
- poster: Main frontal view (00)
- poster2: Lateral angle (07)
- poster3: Frontal detail (02)
- poster4: Alternative angle (01)
Response Structureโ
Success Responseโ
{
"operation": "create",
"documentId": "auto_generated_variant_id",
"skuModel": "20637008650QT",
"success": true,
"message": "New Variants document created for SKU 20637008650QT"
}
Error Responseโ
{
"operation": "error",
"documentId": null,
"skuModel": "UNKNOWN",
"success": false,
"message": "Error in Variants document management: Missing skuModel",
"error": "skuModel missing in mapped data"
}
Brand Integrationโ
The function integrates with the brand management system:
- Automatically finds or creates brands in MainBrands collection
- Uses normalized brand names according to business rules
- Handles brand ID mapping and reference management
- Logs brand operations for debugging and monitoring
Logging and Monitoringโ
Comprehensive logging system for operation tracking:
- Document Operations: Create/update operations with IDs
- Brand Management: Brand find/create operations
- Tag Management: Tag find/create operations for frame colors and sizes
- Error Handling: Detailed error logging with context
- Performance: Operation timing and success/failure tracking
CatalogOrder Integrationโ
When called from populateVariantFromSku, the function:
- Receives `catalogOrdersRef` parameter with CatalogOrder ID
- Links variant to originating catalog order
- Enables traceability from variant back to source order
- Supports batch processing workflows
Brand Normalization Systemโ
The function includes automatic brand normalization to ensure consistent brand naming across all collections.
Brand Mapping Rulesโ
- Hugo brands: "HUGO" โ "HUGO EYEWEAR"
- Boss brands: "HUGO BOSS", "BOSS ORANGE" โ "BOSS EYEWEAR"
- Carrera brands: "CARRERA BY JIMMYCHOO", "CARRERA BIKE", "CARRERA SNOW", "CARRERA DUCATI" โ "CARRERA"
- Polaroid brands: "POLAROID ANCILLARIES", "POLAROID KIDS", "POLAROID STAYSAFE" โ "POLAROID"
- Smith brands: "SMITH FASHION & ACC.", "SMITH BIKE HELMETS", "SMITH SNOW", "SMITH BIKE GOGGLES", "PRIVATE LABEL SMITH", "SUNCLOUD" โ "SMITH OPTICS"
- Other brands: Remain unchanged
Thread-Safe Tag Systemโ
The function utilizes thread-safe tag creation functions to prevent duplicates:
findOrCreateTag()- Creates frame color and size tags with automatic deduplication โ CallsfindOrCreateTagThreadSafe()from tagUtils for mutex-based synchronization- Prevents duplicate Tags documents when processing multiple variants simultaneously
Tag Creation Process:
- Frame Color tags: group="Frame Color", type="frameColor", groupOrder=11
- Size tags: group="Size", type="size", groupOrder=10
- Thread-safe creation with exclusive locks per tag combination
- Automatic cleanup of expired locks (10 minutes timeout)
Related Functionsโ
- populateVariantFromSku - Main workflow function that calls this component
- createProductDocument - Manages Products collection alongside this function
- tagUtils - Provides thread-safe tag creation utilities with mutex synchronization
Function Name: createOrUpdateVariantDocument
Autore: Domenico Cerone Data di creazione: 25/09/2025
Last Reviewer: Domenico Cerone
Trigger: Chiamata da populateVariantFromSku e populateVariantFromExcel
Purpose: Gestisce la creazione e l'aggiornamento dei documenti nella collezione Firestore 'Variants' a partire dai dati JSON mappati generati da populateVariantFromSku. Gestisce il ciclo di vita completo delle varianti con gestione automatica dei tag, integrazione brand e mappatura completa dei campi.
Funzionamento Dettagliatoโ
Questa funzione componente gestisce la gestione completa della collezione Variants con un sofisticato workflow di 3 step sia per nuove varianti che per aggiornamenti di varianti esistenti. Include sistema di creazione tag thread-safe e normalizzazione brand per garantire consistenza dati in scenari di alta concorrenza.
1. CONTROLLO ESISTENZA DOCUMENTOโ
- Cerca nella collezione 'Variants' un documento con skuModel uguale al valore fornito
- Se ESISTE โ aggiorna solo i campi necessari (STEP 3)
- Se NON ESISTE โ crea nuovo documento completo (STEP 2)
2. CREAZIONE NUOVO DOCUMENTOโ
- Crea documento con struttura base completa
- Popola solo i campi mappati dal JSON, lascia gli altri vuoti
- Utilizza ID auto-generato di Firestore
- Imposta status = "Incompleto"
3. AGGIORNAMENTO DOCUMENTO ESISTENTEโ
- Aggiorna solo i campi che provengono dal JSON mappato
- Mantiene tutti gli altri campi esistenti invariati
- Aggiorna lastUpdate con timestamp corrente
Campi Popolati dal JSON Mappatoโ
Campi Mappati Direttamenteโ
- skuModel โ skuModel (identificatore principale)
- eanCode โ eanCode
- frameColor โ frameColor
- lensesColor โ lensesColor
- glassesName โ glassesName
- mainBrandRef โ ID brand (cerca/crea in collezione MainBrands)
- upcCode โ upcCode
- batch โ batch (valore dal CatalogOrder o parametro input)
- productRef โ ID del documento Products padre
- catalogOrdersRef โ ID del CatalogOrder che ha generato la variante
- poster โ poster (vista 00 - frontale principale)
- poster2 โ poster2 (vista 07 - angolazione laterale)
- poster3 โ poster3 (vista 02 - dettaglio frontale)
- poster4 โ poster4 (vista 01 - angolazione alternativa)
Campi Timestamp (con conversione)โ
- lastUpdate โ timestamp corrente (oggetto Date)
- skuReleaseDate โ skuReleaseDate (se presente, oggetto Date)
- skuEndDate โ skuEndDate (se presente, oggetto Date)
- advStartDate โ advStartDate (se presente, oggetto Date)
- advEndDate โ advEndDate (se presente, oggetto Date)
Campo Booleanโ
- isADV โ isADV (convertito da "YES"/"NO" a boolean)
Oggetto Size (tutti i campi come stringhe)โ
- size.bridge โ bridge
- size.frameWidth โ frameWidth
- size.lensHeight โ lensHeight
- size.lensWidth โ lensWidth
- size.size โ size
- size.templeLength โ templeLength
- size.frontHeight โ frontHeight
- size.hingeToHinge โ hingeToHinge
- size.lensCircumference โ lensCircumference
- size.lensAngle โ lensAngle
- size.phantoscopicAngle โ phantoscopicAngle
Array Specialiโ
- list_size_color_tags โ [ID tag frameColor, ID tag size] (cerca/crea nella collezione Tags)
- list_images โ list_images (array di oggetti con view e url)
Sistema Gestione Tagโ
La funzione crea/trova automaticamente tag nella collezione Tags:
Tag Colore Frameโ
- Group: "Frame Color"
- Type: "frameColor"
- GroupOrder: 11
- Name: valore frameColor (es. "BLACK", "BURGUNDY 2")
Tag Sizeโ
- Group: "Size"
- Type: "size"
- GroupOrder: 10
- Name: valore size (es. "54", "99")
Struttura Documento Baseโ
Tutti gli altri campi mantengono i valori di default:
- assignedTo: ""
- assignmentDate: ""
- dataTaken: false
- id: "" (auto-generato da Firestore)
- loadingId: ""
- mainModel: false
- modelPriority: ""
- modelViewerUrl: ""
- modify_model: { rejectCount: "", requestCount: "", status: "" }
- posterNoBackground: ""
- primaryFrameColorHex: ""
- primaryLensesColorHex: ""
- priority: 0
- productRef: ""
- refLogVariant: ""
- secondaryFrameColorHex: ""
- secondaryLensesColorHex: ""
- status: "Incompleto"
- templeColor: ""
- urlDE: ""
- urlES: ""
- urlFR: ""
- urlGlobal: ""
- urlGlobalComplete: ""
- urlGlobalCompleteSize: 0
- urlGlobalSize: 0
- urlProductPage: ""
- urlUsdz: ""
- urlUsdzComplete: ""
- urlUsdzCompleteSize: 0
- urlUsdzSize: 0
- variantCode: ""
- list_notes: []
Parametri Funzioneโ
/**
* @param {Object} mappedJsonData - Dati JSON mappati da populateVariantFromSku
* @param {string} requestId - ID della richiesta per logging
* @param {string} batch - Assegnazione batch della variante (opzionale)
* @param {string} productRef - ID del documento Products padre (opzionale)
* @param {string} catalogOrdersRef - ID del CatalogOrder che ha generato la variante (opzionale)
* @returns {Promise<Object>} Risultato dell'operazione con dettagli
*/
Conversione Campi Dataโ
I campi timestamp vengono automaticamente convertiti da vari formati in oggetti Date JavaScript:
Formati Input Supportatiโ
- Numero: Timestamp Unix in millisecondi
- Stringa: Stringa data ISO 8601 (es. "2025-08-01T02:00:00")
- Vuoto/null: Rimane vuoto
Conversione Automaticaโ
- Tutti i campi data vengono convertiti in oggetti Date JavaScript
- Date vuote o non valide rimangono come stringhe vuote
- Timestamp corrente usato come fallback per errori di conversione
Gestione Immaginiโ
La funzione gestisce array di immagini dal JSON mappato:
Struttura list_imagesโ
[
{
"view": "00",
"url": "https://firebasestorage.googleapis.com/.../image_00.jpg?token=xxx"
},
{
"view": "01",
"url": "https://firebasestorage.googleapis.com/.../image_01.jpg?token=yyy"
},
{
"view": "02",
"url": "https://firebasestorage.googleapis.com/.../image_02.jpg?token=zzz"
}
]
Campi Posterโ
- poster: Vista frontale principale (00)
- poster2: Angolazione laterale (07)
- poster3: Dettaglio frontale (02)
- poster4: Angolazione alternativa (01)
Struttura Responseโ
Response Successoโ
{
"operation": "create",
"documentId": "auto_generated_variant_id",
"skuModel": "20637008650QT",
"success": true,
"message": "Nuovo documento Variants creato per SKU 20637008650QT"
}
Response Erroreโ
{
"operation": "error",
"documentId": null,
"skuModel": "UNKNOWN",
"success": false,
"message": "Errore nella gestione documento Variants: skuModel mancante",
"error": "skuModel mancante nei dati mappati"
}
Integrazione Brandโ
La funzione si integra con il sistema di gestione brand:
- Trova o crea automaticamente brand nella collezione MainBrands
- Utilizza nomi brand normalizzati secondo le regole di business
- Gestisce mappatura ID brand e gestione riferimenti
- Logga operazioni brand per debugging e monitoraggio
Logging e Monitoraggioโ
Sistema di logging completo per tracking delle operazioni:
- Operazioni Documento: Operazioni create/update con ID
- Gestione Brand: Operazioni find/create brand
- Gestione Tag: Operazioni find/create tag per colori frame e taglie
- Error Handling: Logging errori dettagliato con contesto
- Performance: Timing operazioni e tracking successo/fallimento
Integrazione CatalogOrderโ
Quando chiamata da populateVariantFromSku, la funzione:
- Riceve parametro `catalogOrdersRef` con ID CatalogOrder
- Collega variante all'ordine catalogo di origine
- Abilita tracciabilitร dalla variante all'ordine sorgente
- Supporta workflow di batch processing
Sistema Normalizzazione Brandโ
La funzione include normalizzazione automatica dei brand per garantire nomenclatura brand consistente in tutte le collezioni.
Regole Mappatura Brandโ
- Brand Hugo: "HUGO" โ "HUGO EYEWEAR"
- Brand Boss: "HUGO BOSS", "BOSS ORANGE" โ "BOSS EYEWEAR"
- Brand Carrera: "CARRERA BY JIMMYCHOO", "CARRERA BIKE", "CARRERA SNOW", "CARRERA DUCATI" โ "CARRERA"
- Brand Polaroid: "POLAROID ANCILLARIES", "POLAROID KIDS", "POLAROID STAYSAFE" โ "POLAROID"
- Brand Smith: "SMITH FASHION & ACC.", "SMITH BIKE HELMETS", "SMITH SNOW", "SMITH BIKE GOGGLES", "PRIVATE LABEL SMITH", "SUNCLOUD" โ "SMITH OPTICS"
- Altri brand: Rimangono invariati
Sistema Tag Thread-Safeโ
La funzione utilizza funzioni di creazione tag thread-safe per prevenire duplicati:
findOrCreateTag()- Crea tag colore frame e taglie con deduplicazione automatica โ ChiamafindOrCreateTagThreadSafe()da tagUtils per sincronizzazione basata su mutex- Previene documenti Tags duplicati quando si processano piรน varianti simultaneamente
Processo Creazione Tag:
- Tag Frame Color: group="Frame Color", type="frameColor", groupOrder=11
- Tag Size: group="Size", type="size", groupOrder=10
- Creazione thread-safe con lock esclusivi per combinazione tag
- Cleanup automatico lock scaduti (timeout 10 minuti)
Funzioni Correlateโ
- populateVariantFromSku - Funzione workflow principale che chiama questo componente
- createProductDocument - Gestisce la collezione Products insieme a questa funzione
- tagUtils - Fornisce utilitร per creazione tag thread-safe con sincronizzazione mutex